﻿using System;
using System.Net;
using System.Windows;
using System.Text;
using Microsoft.Phone.Info;
using System.Reflection;

namespace Moneyman.Library.Helpers
{
    public class LogHelper
    {
        WebClient client = new WebClient();

        public LogHelper() { }

        public LogHelper(Exception ex)
        {
            this.Exception = ex;
        }

        public DateTime Time { get { return DateTime.Now; } }

        public string TimeSpan
        {
            get { return System.TimeSpan.FromTicks(DateTime.Now.Ticks).ToString(); }
        }
        
        public Exception Exception { get; set; }

        public string Content
        {
            get
            {
                StringBuilder builder = new StringBuilder();

                builder.Append(Time.ToString());
                builder.Append("\r\n\r\n");
                builder.Append(TimeSpan);
                builder.Append("\r\n\r\n");
                builder.Append("\r\n\r\n");

                builder.Append("Exception\r\n\r\n");
                builder.Append("**********\r\n\r\n");
                builder.Append(Exception.Message);
                builder.Append("\r\n\r\n**********\r\n\r\n");
                builder.Append(Exception.StackTrace);
                builder.Append("\r\n\r\n**********\r\n\r\n");
                builder.Append(Exception.GetType().FullName);
                builder.Append("\r\n\r\n**********\r\n\r\n");
                builder.Append(Exception.GetType().Assembly.FullName);
                builder.Append("\r\n\r\n**********\r\n\r\n");


                foreach (object o in this.Exception.Data.Keys)
                {
                    builder.Append(Exception.Data[o].ToString());
                    builder.Append("\r\n");
                }

                builder.Append("\r\n\r\n**********\r\n\r\n");

                Type t = typeof(DeviceStatus);

                PropertyInfo[] properties = t.GetProperties();

                foreach (PropertyInfo property in properties)
                {
                    builder.AppendFormat("{0}:\t{1}", property.Name, property.GetValue(null, null));
                    builder.Append("\r\n");
                }

                return builder.ToString();
            }
        }

        public void Send()
        {

            client.UploadStringCompleted += client_UploadStringCompleted;
            client.UploadStringAsync(new Uri("http://www.zhaorong.me/omnia/feedback/" + TimeSpan + ".txt", UriKind.RelativeOrAbsolute), Content);
        }

        void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            client.UploadStringCompleted -= client_UploadStringCompleted;
            MessageBox.Show(e.Result, e.Error == null ? "" : e.Error.Message, MessageBoxButton.OK);
        }
    }
}
